<template>
  <div class="timing-task">
    <!-- 筛选按钮 -->
    <div class="filter-container">
      <!-- 设置个人号 -->
      <el-select v-model.trim="taskState" placeholder="任务状态" size="small" style="width: 200px" clearable>
        <el-option v-for="item in taskStates" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>

      <el-button style="margin-left: 10px" type="primary" size="small" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
    </div>

    <!-- 数据展示 -->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="circlesList"
      border
      fit
      style="width: 99%"
      highlight-current-row
    >
      <el-table-column prop="remarks" label="任务描述" align="center" min-width="100">
        <template slot-scope="{ row }">
          <div class="circle-content" v-html="row.task_name"></div>
        </template>
      </el-table-column>

      <el-table-column prop="remarks" label="朋友圈内容" align="center" min-width="200" width="300">
        <template slot-scope="{ row }">
          <div class="circle-content" v-html="decodeCircleContent(row.remarks)"></div>
        </template>
      </el-table-column>

      <el-table-column prop="state" label="发送类型" align="center" min-width="70" sortable>
        <template slot-scope="{ row }">
          <span v-if="row.cycle_type === 0">定时发送</span>
          <span v-else-if="row.cycle_type === 1">每天</span>
          <span v-else-if="row.cycle_type === 2">隔天</span>
          <span v-else>{{ row.cycle_type }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="execute_time" label="执行时间" align="center" min-width="120" sortable>
        <template slot-scope="{ row }">
          <p>{{ new Date(row.execute_time).toLocaleString() }}</p>
          <span style="text-align: center;"> - </span>
          <p v-if="isValidTime(row.end_time)">{{ new Date(row.end_time).toLocaleString() }}</p>
        </template>
      </el-table-column>

      <el-table-column prop="createTime" label="创建时间" align="center" min-width="120" sortable>
        <template slot-scope="{ row }">
          <p>创建：{{ new Date(row.createTime).toLocaleString() }}</p>
          <span style="text-align: center;">  </span>
          <p v-if="isValidTime(row.modifyTime)">修改：{{ new Date(row.modifyTime).toLocaleString() }}</p>
        </template>
      </el-table-column>

      <el-table-column prop="state" label="任务状态" align="center" min-width="70" sortable>
        <template slot-scope="{ row }">
          <span v-if="row.state === 1">开启中</span>
          <span v-else-if="row.state === 0">已完成</span>
          <span v-else>{{ row.state }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" min-width="70" class-name="fixed-width">
        <template slot-scope="{ row, $index }">
          <div class="action-buttons">
          <el-button v-if="row.state === 1" size="mini" class="action-button" type="primary" @click="editTask(row, $index)">修改</el-button>
          <el-button size="mini" class="action-button" type="danger"  @click="deleteTask(row, $index)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <Pagination
      v-show="total > 0"
      :total="total"
      :page.sync="pageNo"
      :limit.sync="pageSize"
      @pagination="getCirclesList"
    />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

import Pagination from '@/components/Pagination'

import { queryCircleTask, deleteCircleTask } from '@/api/front/circle'

export default {
  name: 'TimingTask',
  components: { Pagination },
  data() {
    return {
      taskStates: [
        {
          label: '开启中',
          value: 1
        },
        {
          label: '已完成',
          value: 0
        }
      ], // 任务状态
      taskState: '', // 任务状态

      listLoading: true, // 正在获取数据
      circlesList: [], // 表格中的数据

      total: 0, // 数据总数
      pageNo: 1, // 页
      pageSize: 20, // 页面大小
      tableKey: 0 // 表的key 改变可以重新渲染表
    }
  },
  computed: {
    ...mapGetters({
      currentUser: 'currentUser'
    })
  },
  created() {
    // 获取朋友圈列表
    this.getCirclesList()
  },
  methods: {
    // 分页查询设备
    getCirclesList() {
      queryCircleTask(this.currentUser.SupplierId, this.pageNo, this.pageSize, this.taskState)
        .then((res) => {
          this.circlesList = res?.data?.rows || []
          this.total = res?.data?.records || 0
          this.listLoading = false
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    // 搜索
    handleFilter() {
      this.pageNo = 1
      this.getCirclesList()
    },
    // 解析朋友圈内容
    decodeCircleContent(content) {
      try {
        const jContent = JSON.parse(content)
        const { circleType, textContent, attachtContent } = jContent
        let AttachContent = []
        if (attachtContent) {
          AttachContent = attachtContent.split(',')
        }
        if (circleType === 'text') {
          return `<p>${textContent}</p>`
        } else if (circleType === 'picture') {
          let imgStr = ''
          for (const ac of AttachContent) {
            imgStr = imgStr + `<img style="width:33%;padding:5px;" src="${ac}" />`
          }
          return `<p>${textContent}</p>
              <div style="display:flex;flex-wrap:wrap;">${imgStr}</div>
              `
        } else if (circleType === 'video') {
          return `<p>${textContent}</p>
            <video style="padding:5px;" src="${attachtContent}" controls></video>
            `
        } else {
          // 链接
          const title = AttachContent[1]
          const imgUrl = AttachContent[2]
          return `<p>${textContent}</p>
            <div style="display:flex;align-items:center;">
            <img style="width:30%;margin-right:5px;" src="${imgUrl}" />
            <span>${title}</span>
            </div>
            `
        }
      } catch (error) {
        return content
      }
    },
    // 删除任务
    deleteTask(row) {
      this.$confirm('此操作将删除该任务, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteCircleTask(row.id).then(() => {
            this.getCirclesList()
          })
        })
        .catch(() => {})
    },
    // 编辑任务
    editTask(row) {
      this.$store.commit('circleManager/SET_CIRCLE_DATA', row)
      this.$store.commit('circleManager/SET_EDIT_MODE', true)
      this.$store.commit('circleManager/SET_CURRENT_CIRLCLE_NAV', 'sendCircle')
    },
    // 校验时间是否有效
    isValidTime(timestamp) {
      if (!timestamp) return false
      const date = new Date(timestamp)
      return !isNaN(date.getTime())
    }
  }
}
</script>

<style lang="scss" scoped>
.timing-task {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;

  .filter-container {
    margin-bottom: 20px;
  }
  ::v-deep .circle-content {
    flex: 1 1 auto;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    p {
      padding: 5px;
      text-align: start;
    }
  }
}
.action-buttons {
  display: grid;
  gap: 12px; /* 按钮间距 */
  justify-content: center;
}

.action-button {
  width: 60px; /* 统一按钮宽度 */
  margin: 0 !important; /* 清除默认边距 */
}
</style>
